const express = require('express');
const bcrypt = require('bcryptjs');
const { Op } = require('sequelize');
const Student = require('../models/StudentRegister');

const router = express.Router();

// 学生注册
router.post('/registerStudent', async (req, res) => {
  try {
    const { name, student_no, gender, id_card, password } = req.body;

    // 1️⃣ **字段验证**
    if (!name || !student_no || !id_card || !password) {
      return res.status(400).json({ success: false, message: '请填写所有必需的字段' });
    }

    if (!/^\d{17}[\dXx]$/.test(id_card)) {
      return res.status(400).json({ success: false, message: '身份证号格式不正确' });
    }

    if (!/^\d{8,12}$/.test(student_no)) {
      return res.status(400).json({ success: false, message: '学号格式不正确' });
    }

    // 2️⃣ **检查学号和身份证号是否已注册**
    const existingStudent = await Student.findOne({
      where: {
        [Op.or]: [{ student_no }, { id_card }]
      }
    });

    if (existingStudent) {
      return res.status(400).json({
        success: false,
        message: '该学号或身份证号已被注册'
      });
    }

    // 3️⃣ **密码加密**
    const hashedPassword = await bcrypt.hash(password, 10);

    // 4️⃣ **创建学生**
    const newStudent = await Student.create({
      name,
      student_no,
      gender: gender || '保密',
      id_card,
      password: hashedPassword,
      points: 0
    });

    // 5️⃣ **返回成功信息**
    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        id: newStudent.id,
        name: newStudent.name,
        student_no: newStudent.student_no,
        gender: newStudent.gender
      }
    });

  } catch (error) {
    console.error('注册学生失败:', error);
    res.status(500).json({ success: false, message: '服务器错误，请稍后重试' });
  }
});

module.exports = router;
